package com.topica.network;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.serialization.PropertyInfo;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.topica.database.DataBaseHelper;
import com.topica.database.task.TopicaDBTask;
import com.topica.network.callback.OnGetListCourseUpdateListener;
import com.topica.object.CourseItem;
import com.topica.object.CourseUpdate;

public class GetListUpdate extends TopicaDBTask {
	private String user;
	private ArrayList<CourseUpdate> listUpdate;
	private final static String METHOD = "checkCourseUpdate";
	private static final String TAG = "GetListUpdate";
	private OnGetListCourseUpdateListener listener;

	public GetListUpdate(Context context, String username) {
		super(context);
		user = username;
	}

	@Override
	protected Integer doInBackground(Void... params) {
		DataBaseHelper myDbHelper = new DataBaseHelper(
				context.getApplicationContext());
		ArrayList<CourseItem> mCourse = myDbHelper.getListCourse();
		myDbHelper.close();
		String listCourse = "{\"listcourse\":[";
		for (int i = 0, n = mCourse.size(); i < n; i++) {
			listCourse += "{\"course_id\":" + mCourse.get(i).getId() + "},";
		}
		if (!mCourse.isEmpty()) {
			listCourse = listCourse.substring(0, listCourse.length() - 1);
		}
		listCourse += "]}";
		PropertyInfo info = new PropertyInfo();
		info.setName("user_id");
		info.setValue(user);
		Log.e(TAG,"listCourse = " + listCourse);
		PropertyInfo info1 = new PropertyInfo();
		info1.setName("ListCourse");
		info1.setValue(listCourse);

		List<PropertyInfo> pp = new ArrayList<PropertyInfo>();
		pp.add(info);
		pp.add(info1);
		SoapCaller caller = new SoapCaller();
		String result = caller.getString(METHOD, pp);
		Log.e(TAG, "Result = " + result);
		listUpdate = new ArrayList<CourseUpdate>();
		try {
			JSONObject json = new JSONObject(result);
			JSONArray arr = json.getJSONArray("listcourse");
			for (int i = 0; i < arr.length(); i++) {
				CourseUpdate item = new CourseUpdate();
				JSONObject course = arr.getJSONObject(i);
				item.setCourseId(course.getInt("course_id"));
				item.setStatus(course.getString("status"));
				item.setFullname(course.getString("fullname"));
				listUpdate.add(item);
			}
		} catch (JSONException e) {
			e.printStackTrace();
			return FAIL;
		}
		return OK;
	}

	@Override
	protected void onPostExecute(Integer result) {
		super.onPostExecute(result);
		if (result == OK) {
			listener.onGetListCourseUpdateListener(listUpdate);
		} else {
			Toast.makeText(context.getApplicationContext(), "Update Fail",
					Toast.LENGTH_SHORT).show();
		}
	}

	public void setOnGetListCourseUpdateListener(
			OnGetListCourseUpdateListener listener) {
		this.listener = listener;
	}
}
